<template>
<div 
    class="my-chart-el"
    ref="MyChart">
    <canvas
        ref="Canvas">
    </canvas>
</div>
</template>
<script>
/*
 echart封装组件,自适应高度宽度,动态或配置项
 */
import {TaskControl} from '@/common/SimpleAnimation';
const taskServe = new TaskControl();
export default {
    name:'MyChart',
    data() {
        this.timer;
        this.chart;  //echart实例
        return {};
    },
    methods:{
        /*
         写入配置项(外部调用)
         getOption:function获取配置项的回调
         */
        setOption(getOption=()=>{}){  
            if(typeof getOption !== 'function') return;
            const MyChart = this.$refs.MyChart;
            const Canvas = this.$refs.Canvas;
            taskServe.clear(this.timer);
            this.timer = taskServe.add(()=>{
                if(Canvas.height == MyChart.clientHeight && Canvas.width == MyChart.clientWidth) return;
                Canvas.height = MyChart.clientHeight;
                Canvas.width = MyChart.clientWidth;
                if(this.chart){
                    this.chart.dispose();  //销毁
                }
                this.chart = this.$echarts.init(Canvas);
                this.chart.setOption(getOption());
            });
            return this.chart;
        },
    },
    destroyed(){
        taskServe.clear(this.timer);
    },
};
</script>
<style scoped lang="scss">
.my-chart-el{
    width: 100%;
    height: 100%;
    position: relative !important;
    canvas{
        position: absolute !important;
        left: 0;
        right: 0;
    }
}
</style>
